'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from dopplershift.core.containers.mediator import getMediator
from dopplershift.core.exc import DSException
from lxml import etree
import os
import logging
logger = logging.getLogger(__name__)

class ErrorTemplateNotFound(DSException):
    '''
    Error raised if not specified or not found error template file
    '''

class TemplateLoader:
    def __init__(self):
        self._container = {}
        cfg = getMediator().get('CollectorConfig')
        self._templates_path = cfg.get_templates_path()
        self._access_control = etree.XSLTAccessControl(read_network=False, read_file=True)
        self._reload_template = cfg.get_reload_template()
        self._errors_templates = {}
        if self._reload_template == 'true':
            self._reload_template = True
        else:
            self._reload_template = False
        self._loadTemplates(cfg)
    def _loadTemplates(self, cfg):
        for el in cfg.get_templates_all():
            self._loadTemplate(el)
        for el in ['404', '403', '500']:
            tmpl_path = cfg.get_error_template_path(el)
            if tmpl_path is None:
                raise ErrorTemplateNotFound(el)
            tmpl = self._loadTemplate(tmpl_path)
            if  tmpl is None:
                raise ErrorTemplateNotFound(el)
            self._errors_templates[el] = tmpl
        
    def _loadTemplate(self, template_filename):
        file_name=os.path.join(self._templates_path, template_filename)
        if os.path.isfile(file_name):
            try:
                self._container[template_filename] = etree.XSLT(
                                                        etree.parse(
                                                                  open(file_name)
                                                                  ), access_control=self._access_control
                                                        )
            except:
                logger.error("{_loadTemplate}, except error while opening <%s> file"%(template_filename))
                return False
            return self._container[template_filename]
        else:
            logger.error("Template with filename %s not found in path %s"%(template_filename, self._templates_path))
    def getErrorTemplate(self, error_code):
        return self._errors_templates.get(str(error_code))
    def getTemplate(self, template_name):
        if self._reload_template == False and template_name in self._container:
            return self._container.get(template_name)
        return self._loadTemplate(template_name)
    def reload(self):
        cfg = getMediator().get('CollectorConfig')
        self._loadTemplates(cfg)
        errors = []
        loaded = 0
        for k,v in self._container.iteritems():
            if v is None or v is False: errors.append(k)
            else: loaded += 1
        return {"errors": errors, "loaded": loaded, "cnt": len(self._container)}